﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Threading;

namespace Howork
{
    public class FileAdapter
    {
        public static String tempFolder = "D://temp/";

        public static String getCSV(List<DeviceUsage> his, String fileName)
        {
            if(Directory.Exists(tempFolder)==false)
            {
                Directory.CreateDirectory(tempFolder);
            }
            if(isValidFileName(fileName) == false)
            {
                return null;
            }
            String tempFileName = tempFolder + fileName;
            FileStream fs = new FileStream(tempFileName, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("utf-8"));
            //sw.WriteLine("Hello");
            sw.WriteLine("设备名称,设备类型,开始使用时间,结束使用时间,使用人");
            foreach (DeviceUsage du in his)
            {
                sw.WriteLine("{0},{1},{2},{3},{4}", du.device_name,du.typeName, du.timeFrom, du.timeTo, du.userID);
            }


            sw.Close();
            fs.Close();
            return tempFileName;
        }

        private static bool isValidFileName(string fileName)   //判断文件名是否合法
        {
            bool isValid = true;
            string errChar = "\\/:*?\"<>|";
            if (string.IsNullOrEmpty(fileName))
            {
                isValid = false;
            }
            else
            {
                for (int i = 0; i < errChar.Length; i++)
                {
                    if (fileName.Contains(errChar[i].ToString()))
                    {
                        isValid = false;
                        break;
                    }
                }
            }
            return isValid;
        }

       

        public static bool provideCSVDownload(HttpRequest _Request, HttpResponse _Response, String _file, long _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    int pack = 10240; //10K bytes
                    //int sleep = 200;   //每秒5次   即5*10K bytes每秒
                    int sleep = (int)(Math.Floor(1000d * pack / _speed)) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    String fileName = _file.Substring(_file.LastIndexOf('/')+1);
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}